package com.gitee.cui.zookeeper.nameservice;

import com.gitee.cui.zk.ClientFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

/**
 * ID生成器
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021-11-06 11:41
 **/
public class IDMaker {

	private static final String ZK_ADDRESS = "127.0.0.1:2181";

	private CuratorFramework client = null;

	/**
	 * 初始化客户端
	 */
	public void init() {
		client = ClientFactory.createSimple(ZK_ADDRESS);
		client.start();
	}

	/**
	 * 关闭客户端
	 */
	public void close() {
		if (client != null) {
			client.close();
		}
	}

	/**
	 * 生成唯一id
	 * @param nodeName 节点名称
	 * @return id
	 */
	public String makeId(String nodeName) {
		// 创建有序节点
		String seqNode = createSeqNode(nodeName);
		if (StringUtils.isEmpty(seqNode)) {
			return null;
		}

		int index = seqNode.lastIndexOf(nodeName);
		if (index >= 0) {
			index += nodeName.length();
			return index <= seqNode.length() ? seqNode.substring(index) : "";
		}
		return seqNode;
	}

	/**
	 * 创建有序节点
	 * @param nodeName 节点前缀
	 * @return 有序节点路径
	 */
	private String createSeqNode(String nodeName) {
		String path = null;
		try {
			path = client.create()
					.creatingParentsIfNeeded()
					.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
					.forPath(nodeName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return path;
	}
}
